package com.laizhenghua.demo.service.impl;

import com.laizhenghua.demo.domain.po.UserEntity;
import com.laizhenghua.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@ConditionalOnProperty(name = "data.type", havingValue = "memory")
@Service
@Slf4j
public class MemoryUserServiceImpl implements UserService, InitializingBean {
    private static final Map<String, UserEntity> USER_CACHE_MAP = new ConcurrentHashMap<>();

    private static final AtomicLong ID_SEQ = new AtomicLong();

    private PasswordEncoder passwordEncoder;

    public MemoryUserServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserEntity getUserByName(String username) {
        return USER_CACHE_MAP.get(username);
    }

    @Override
    public UserEntity saveUser(UserEntity userEntity) {
        String encodePassword = passwordEncoder.encode(userEntity.getPassword());
        userEntity.setPassword(encodePassword);
        if (userEntity.getId() == null) {
            userEntity.setId(ID_SEQ.incrementAndGet());
        }
        USER_CACHE_MAP.put(userEntity.getUsername(), userEntity);
        return userEntity;
    }

    @Override
    public void afterPropertiesSet() {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1L);
        userEntity.setUsername("admin");
        userEntity.setPassword("123456");
        log.info("初始化用户 {}", userEntity);
        saveUser(userEntity);
    }
}
